import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';

import ContractLayout from '@/component/contract/Layout';
import MTable from '@/component/common/MTable';
import { Pagination, Form, Input, Select, DatePicker } from 'antd';

const FormItem = Form.Item;
const Option = Select.Option;
const { RangePicker } = DatePicker;

import contractStyle from './contract.scss';
import MModal from "../../component/common/MModal";
const mConfirm = MModal.confirm;

import FilterListPage from '@/component/common/FilterListPage';
import ApiHelper from '@/store/ApiHelper';
import StoreListMini from '@/store/StoreListMini';
import BrokerListMini from '@/store/BrokerListMini';

import { contract_list, contract_agree, contract_refuse } from '@/constants/ApiTypes';
import { API_URL } from '@/config';
import adminType from '@/tool/adminType';

// const testData = [
//     { a: '12345678', b: '合租', c: '吴超', d: '乔司', e: '1200元', f: '哼哒哥', g: '12345678901', h: '2017-10-08至2018-10-07', i: '月付', j: '1200元' },
//     { a: '12345678', b: '合租', c: '吴超', d: '乔司', e: '1200元', f: '哼哒哥', g: '12345678901', h: '2017-10-08至2018-10-07', i: '月付', j: '1200元' },
//     { a: '12345678', b: '合租', c: '吴超', d: '乔司', e: '1200元', f: '哼哒哥', g: '12345678901', h: '2017-10-08至2018-10-07', i: '月付', j: '1200元' }
// ];

@observer class Filter extends Component {
    static propTypes = {
        form: PropTypes.any,
        onSubmit: PropTypes.func
    };
    handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                if (this.props.onSubmit) {
                    for (let key in values) {
                        if (values[key] === '') delete values[key];
                        //处理date_range
                        if (key == 'date_range') {
                            if (Array.isArray(values[key]) && values[key].length > 0) {
                                values.start_time = values[key][0].unix();
                                values.end_time =  values[key][1].unix();
                            }
                            delete values[key];
                        }
                    }
                    this.props.onSubmit(values);
                }
            }
        });
    };
    selectStore = value => {
        this.props.form.setFieldsValue({ broker_name: '' });
        if (value == '') {
            return BrokerListMini.info.clear();
        }
        BrokerListMini.getInfo(value);
    };
    render() {
        const { getFieldDecorator } = this.props.form;
        const storeListMini = StoreListMini.info;
        const brokerListMini = BrokerListMini.info;

        let storeOptionList = storeListMini.map((val, index) => {
            return <Option key={index} value={`${val.store_id}`}>{val.store_name}</Option>;
        });
        let brokerOptionList = brokerListMini.map((val, index) => {
            return <Option key={index} value={`${val.realname}`}>{val.realname}</Option>;
        });
        return (
            <Form layout="inline" onSubmit={this.handleSubmit}>
                {adminType() == 1 &&
                <FormItem label="门店">
                    {getFieldDecorator('store_id', {
                        initialValue: ''
                    })(
                        <Select placeholder="选择门店" style={{ width: 150 }} onChange={this.selectStore}>
                            <Option key="default" value="">不限</Option>
                            {storeOptionList}
                        </Select>
                    )}
                </FormItem>}
                <FormItem label="经纪人">
                    {getFieldDecorator('broker_name', {
                        initialValue: ''
                    })(
                        <Select placeholder="选择经纪人" style={{ width: 150 }}>
                            <Option key="default" value="">不限</Option>
                            {brokerOptionList}
                        </Select>
                    )}
                </FormItem>
                <FormItem label="合同编号">
                    {getFieldDecorator('contract_no', {
                        initialValue: ''
                    })(
                        <Input/>
                    )}
                </FormItem>
                <FormItem label="创建时间">
                    {getFieldDecorator('date_range', {
                        initialValue: ''
                    })(
                        <RangePicker/>
                    )}
                </FormItem>
                <FormItem>
                    <button className={contractStyle['submit-btn']} type="submit">搜索</button>
                </FormItem>
            </Form>
        );
    }
}
const FilterWrapped = Form.create()(Filter);

@observer class ContractConfirm extends FilterListPage {
    constructor(props) {
        super(props);
        this.defaultQuery = {
            contract_type: 1 //审核合同列表
        };
        this.listApiType = contract_list;
    }
    async pageDidMount() {
        const result = await StoreListMini.getInfo();
        if (!result) return;
        this._setState({ loading: false });
    }
    passContract = (contract_no, broker_id) => {
        mConfirm({
            title: '通过合同',
            content: '通过合同后，请通知租客在签约已完成中及时支付房租，并提醒经纪人在APP已签约中填写附件单并确认。',
            contentStyle: { width: 320, height: 160 },
            okText: '通过',
            showTopClose: false,
            onOk: async () => {
                //通过合同
                const data = { contract_no, broker_id };
                const result = await ApiHelper.requestPost(contract_agree, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '操作成功', duration: 1.5 });
                    this.refresh();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() {}
        });
    };
    rejectContract = (contract_no, broker_id) => {
        mConfirm({
            title: '否决合同',
            content: '合同否决后，请通知经纪人到待签约中重新填写合同，并让租客重新签订。确认。',
            contentStyle: { width: 320, height: 160 },
            okText: '否决',
            showTopClose: false,
            onOk: async () => {
                //否决合同
                const data = { contract_no, broker_id };
                const result = await ApiHelper.requestPost(contract_refuse, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: result.info, duration: 1.5 });
                    this.refresh();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() {}
        });
    };
    render() {
        const { dataList, spinning } = this.state;
        const { passContract, rejectContract } = this;
        const columns = [
            { title: '合同编号', dataIndex: 'contract_no', align: 'middle' },
            { title: '租赁方式', dataIndex: 'rent_type', align: 'middle' },
            { title: '经纪人', dataIndex: 'broker_name', align: 'middle' },
            { title: '物业地址', dataIndex: 'community', align: 'middle' },
            { title: '租金', dataIndex: 'rent_info', align: 'middle', render: (text, record, dataIndex) => isNaN(text) ? text : text / 100 + '元' },
            { title: '客户', dataIndex: 'renter_name', align: 'middle' },
            { title: '联系电话', dataIndex: 'renter_mobile', align: 'middle' },
            { title: '租期', dataIndex: 'rent_time', align: 'middle' },
            { title: '付款', dataIndex: 'pay_type', align: 'middle' },
            { title: '押金', dataIndex: 'deposit', align: 'middle', render: (text, record, dataIndex) => isNaN(text) ? text : text / 100 + '元' },
            { title: '操作', dataIndex: 'k', align: 'middle', render: (text, record, dataIndex) => {
                return (
                    <div>
                        <a href={`${API_URL}/${record.contract_url}`} className={contractStyle['btn-default']} target="_blank">查看合同</a>
                        <a href="javascript:void(0);" className={contractStyle['btn-success']} onClick={() => passContract(record.contract_no, record.broker_id)}>通过</a>
                        <a href="javascript:void(0);" className={contractStyle['btn-warn']} onClick={() => rejectContract(record.contract_no, record.broker_id)}>否决</a>
                    </div>
                );
            } }
        ];
        return (
            <ContractLayout loading={this.state.loading}>
                <div className={contractStyle['top-filter']}>
                    <FilterWrapped onSubmit={this.getDataListWithFilter} />
                </div>
                <MTable columns={columns} dataSource={dataList} spinning={spinning}/>
                <div className="pagination">
                    {this.state.total > 0 && <Pagination showQuickJumper current={this.state.current_page} pageSize={10} total={this.state.total} onChange={this.pageOnChange} />}
                </div>
            </ContractLayout>
        );
    }
}

export default ContractConfirm;